<template>
  <div>
    <el-button type="primary" @click="handleAdd">新增任务</el-button>
    <!-- <el-button type="warning" @click="importData">导入数据</el-button> -->
     <!-- <el-button type="success" @click="exportData">导出数据</el-button> -->
    
    <el-table :data="filteredTodos" style="margin-top: 15px;" v-loading="loading">
      <el-table-column prop="title" label="任务" sortable></el-table-column>
      <el-table-column prop="priority" label="优先级" width="120" sortable>
        <template #default="scope">
          <el-tag :type="priorityTypes[scope.row.priority].type">
            {{ priorityTypes[scope.row.priority].text }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="dueDate" label="截止日期" width="150" sortable>
        <template #default="{row}">
          {{ formatDate(row.dueDate) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="mini" @click="editTodo(scope.row)">编辑</el-button>
          <el-button 
            size="mini" 
            type="danger" 
            @click="confirmDelete(scope.row)"
            :loading="deletingId === scope.row.id">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑对话框 -->
    <el-dialog 
      :title="currentTodo.id ? '编辑任务' : '新增任务'" 
      :visible.sync="showDialog"
      @closed="resetForm">
      <el-form :model="currentTodo" ref="todoForm" :rules="rules">
        <el-form-item label="任务名称" prop="title">
          <el-input v-model="currentTodo.title" placeholder="请输入任务内容"></el-input>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="currentTodo.priority" style="width: 100%">
            <el-option 
              v-for="(item, key) in priorityTypes"
              :key="key"
              :label="item.text"
              :value="key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="截止日期">
          <el-date-picker
            v-model="currentTodo.dueDate"
            type="date"
            placeholder="选择截止日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="showDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="submitForm"
          :loading="saving">
          {{ currentTodo.id ? '更新' : '保存' }}
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import idb from '@/utils/idb';
import { formatDate } from '@/utils/date';

export default {
  props: {
    projectId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      todos: [],
      loading: false,
      saving: false,
      deletingId: null,
      showDialog: false,
      currentTodo: this.getDefaultTodo(),
      priorityTypes: {
        high: { text: '紧急', type: 'danger' },
        medium: { text: '一般', type: 'warning' },
        low: { text: '低', type: 'success' }
      },
      rules: {
        title: [
          { required: true, message: '请输入任务名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
        ],
        priority: [
          { required: true, message: '请选择优先级', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    filteredTodos() {
      return this.todos.filter(todo => todo.projectId === this.projectId);
    }
  },
  created() {
    this.loadTodos();
  },
  methods: {
    getDefaultTodo() {
      return {
        id: null,
        projectId: this.projectId,
        title: '',
        priority: 'medium',
        dueDate: '',
        status: 'pending',
        createdAt: null,
        updatedAt: null
      }
    },

    formatDate,

    async loadTodos() {
      this.loading = true;
      try {
        // 获取当前项目的所有任务
        const allTodos = await idb.getAll('todos');
        this.todos = allTodos.filter(t => t.projectId === this.projectId);
        // this.todos = await idb.getAllByIndex('todos', 'projectId', this.projectId);
      } catch (error) {
        console.error('加载任务失败:', error);
        this.$message.error('加载任务失败');
      } finally {
        this.loading = false;
      }
    },

    handleAdd() {
      this.currentTodo = this.getDefaultTodo();
      this.showDialog = true;
    },

    editTodo(todo) {
      this.currentTodo = { ...todo };
      this.showDialog = true;
    },

    resetForm() {
      this.$refs.todoForm?.resetFields();
    },

    async submitForm() {
      try {
        const valid = await this.$refs.todoForm.validate();
        if (!valid) return;

        this.saving = true;
        const now = new Date().toISOString();

        const todoData = {
          ...this.currentTodo,
          updatedAt: now,
          projectId: this.projectId
        };

        if (!todoData.id) {
          // 新增任务
          todoData.id = `todo_${Date.now()}`;
          todoData.createdAt = now;
          await idb.add('todos', todoData);
          this.$message.success('任务添加成功');
        } else {
          // 更新任务
          await idb.update('todos', todoData);
          this.$message.success('任务更新成功');
        }

        this.showDialog = false;
        await this.loadTodos();
      } catch (error) {
        console.error('保存失败:', error);
        this.$message.error('保存任务失败');
      } finally {
        this.saving = false;
      }
    },

    confirmDelete(todo) {
      this.$confirm(`确定删除任务"${todo.title}"吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteTodo(todo.id);
      }).catch(() => {});
    },

    async deleteTodo(id) {
      this.deletingId = id;
      try {
        await idb.delete('todos', id);
        this.$message.success('任务已删除');
        await this.loadTodos();
      } catch (error) {
        console.error('删除失败:', error);
        this.$message.error('删除任务失败');
      } finally {
        this.deletingId = null;
      }
    },
    async exportData() {
      try {
        this.$message.info('正在导出数据...');
        await idb.exportAndDownload(`project_backup_${new Date().toISOString().slice(0,10)}.json`);
        this.$message.success('数据导出成功');
      } catch (error) {
        console.error('导出失败:', error);
        this.$message.error('数据导出失败');
      }
    },
     importData() {
      // 导入功能实现...
    }
  },
  watch: {
    projectId() {
      this.loadTodos();
    }
  }
}
</script>

<style scoped>
.el-table {
  margin-top: 15px;
}
</style>